﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace DNNspot.LiveChat.DataModel
{
    public partial class Session
    {
        public static Session Create(int portalId, int categoryId, int clientId, string urlReferrer, string question, string notes)
        {
            var session = new Session();
            session.PortalId = portalId;
            session.CategoryId = categoryId;
            session.ClientId = clientId;
            session.Question = question;
            session.UrlReferrer = urlReferrer;
            session.Notes = notes;

            session.Save();

            return session;
        }

        public static Session Load(int? sessionId)
        {
            var session = new Session();

            if (sessionId != null)
                session.LoadByPrimaryKey(Convert.ToInt32(sessionId));

            return session;
        }
    }

    public partial class SessionCollection
    {
        public static int GetTotal(FlexigridSearchCriteria searchCriteria)
        {
            var tmpNumber = searchCriteria.PageNumber;
            var tmpSize = searchCriteria.PageSize;

            searchCriteria.PageNumber = -1;
            searchCriteria.PageSize = -1;

            var count = Search(searchCriteria).Count;

            searchCriteria.PageNumber = tmpNumber;
            searchCriteria.PageSize = tmpSize;

            return count;
        }

        public static List<Session> Search(FlexigridSearchCriteria searchCriteria)
        {
            var q = new SessionQuery();

            if (searchCriteria.PageNumber > 0 && searchCriteria.PageSize > 0)
            {
                q.es.PageNumber = searchCriteria.PageNumber;
                q.es.PageSize = searchCriteria.PageSize;
            }

            q.Where(q.PortalId == searchCriteria.PortalId);

            foreach (String keyword in searchCriteria.Query.Split(' '))
            {
                q.And(string.Format("{0} LIKE '%{1}%'", searchCriteria.QueryColumns, keyword));
            }

            q.OrderBy(searchCriteria.SortColumn, searchCriteria.SortDirection);

            var sessions = new SessionCollection();
            sessions.Load(q);

            return sessions;
        }
    }
}
